package com.oss.intercept.jwt;

import com.oss.utils.StringUtils;
import com.oss.utils.constants.DataDictionary;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

public class JWTHelper {

	/**
	 * 密钥加密token
	 *
	 * @return
	 * @throws Exception
	 */
	public static String generateToken(IJWTInfo ijwtInfo, String priKeyPath, int exprie) throws Exception {

		String compactJws = Jwts.builder().setSubject(ijwtInfo.getUniqueName())
				.claim(DataDictionary.JWT_KEY_USER_ID, ijwtInfo.getId())
				.claim(DataDictionary.JWT_KEY_NAME, ijwtInfo.getName())
				.setExpiration(DateTime.now().plusSeconds(exprie).toDate())
				.signWith(SignatureAlgorithm.RS256, KeyHelper.getPrivateKey(priKeyPath)).compact();
		return compactJws;
	}

	/**
	 * 公钥解析token
	 *
	 * @param token
	 * @return
	 * @throws Exception
	 */
	public static Jws<Claims> parserToken(String token, String pubKeyPath) throws Exception {
		Jws<Claims> claimsJws = Jwts.parser().setSigningKey(KeyHelper.getPublicKey(pubKeyPath)).parseClaimsJws(token);
		return claimsJws;
	}

	/**
	 * 获取token中用户信息
	 *
	 * @param token
	 * @param pubKeyPath
	 * @return
	 * @throws Exception
	 */
	public static IJWTInfo getInfoFromToken(String token, String pubKeyPath) throws Exception {
		Jws<Claims> claimsJws = parserToken(token, pubKeyPath);
		Claims body = claimsJws.getBody();
		return new JWTInfo(body.getSubject(), StringUtils.getObjectValue(body.get(DataDictionary.JWT_KEY_USER_ID)),
				StringUtils.getObjectValue(body.get(DataDictionary.JWT_KEY_NAME)));

	}

}
